package com.quyunshuo.androidbaseframemvvm.base.mvvm.v

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit

object PrefsManager {

    lateinit var prefs: SharedPreferences

    // 统一管理所有键名
    object Keys {
        const val USER_NAME = "user_name"
        const val IS_LOGIN = "is_login"
        const val TOKEN = "access_token"
        const val LAST_UPDATE_TIME = "last_update_time"
        const val USER_ID = "user_id"
        const val NOTIFICATION_ENABLED = "notification_enabled"


        const val LANGUAGE = "language"
        const val FIRST_GUIDE = "first_guide"
    }

    // 初始化（必须在 Application 中调用）
    fun initialize(context: Context) {
        prefs = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
    }

    // 通用保存方法
    open inline fun <reified T> save(key: String, value: T) {
        prefs.edit(commit = false) {
            when (value) {
                is String -> putString(key, value)
                is Int -> putInt(key, value)
                is Long -> putLong(key, value)
                is Float -> putFloat(key, value)
                is Boolean -> putBoolean(key, value)
                else -> throw IllegalArgumentException("Unsupported type")
            }
        }
    }

    // 通用读取方法
    open inline fun <reified T> read(key: String, defaultValue: T): T {
        return when (defaultValue) {
            is String -> prefs.getString(key, defaultValue) as T
            is Int -> prefs.getInt(key, defaultValue) as T
            is Long -> prefs.getLong(key, defaultValue) as T
            is Float -> prefs.getFloat(key, defaultValue) as T
            is Boolean -> prefs.getBoolean(key, defaultValue) as T
            else -> throw IllegalArgumentException("Unsupported type")
        }
    }

    // 删除键值
    fun remove(key: String) = prefs.edit { remove(key) }

    // 清空所有数据
    fun clear() = prefs.edit { clear() }

    // 是否包含某个键
    fun contains(key: String): Boolean = prefs.contains(key)

    /******************** 封装常用属性的访问 ********************/
    var userName: String
        get() = read(Keys.USER_NAME, "")
        set(value) = save(Keys.USER_NAME, value)

    var userId: Int
        get() = read(Keys.USER_ID, 0)
        set(value) = save(Keys.USER_ID, value)

    var isLogin: Boolean
        get() = read(Keys.IS_LOGIN, false)
        set(value) = save(Keys.IS_LOGIN, value)

    var token: String
        get() = read(Keys.TOKEN, "")
        set(value) = save(Keys.TOKEN, value)

    var lastUpdateTime: Long
        get() = read(Keys.LAST_UPDATE_TIME, 0L)
        set(value) = save(Keys.LAST_UPDATE_TIME, value)

    var isNotificationEnabled: Boolean
        get() = read(Keys.NOTIFICATION_ENABLED, true)
        set(value) = save(Keys.NOTIFICATION_ENABLED, value)
}